package com.ruyuan.commodity.client;

import com.ruyuan.commodity.api.GoodsIndexClient;
import com.ruyuan.commodity.common.mamager.GoodsInfoIndexManager;
import com.ruyuan.commodity.domain.FullUpdateIndexRequest;
import com.ruyuan.commodity.domain.IndexRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;

/**
 *  商品索引的对外接口实现类
 */
@RestController
public class GoodsIndexClientDefaultImpl implements GoodsIndexClient {

    private static final Logger LOG = LoggerFactory.getLogger(GoodsIndexClientDefaultImpl.class);

    /**
     * 商品索引管理器
     */
    @Autowired
    private GoodsInfoIndexManager goodsInfoIndexManager;

    /**
     * 将某个商品加入索引
     * @param request 新增商品索引的请求对象
     * @return 处理结果
     */
    @Override
    public Boolean addIndex(IndexRequest request) {
        try {
            goodsInfoIndexManager.addIndex(request.getGoodsInfoMap());
            return true;
        } catch (Exception e) {
            LOG.error("addIndex发生异常", e);
            return false;
        }
    }

    /**
     * 更新某个商品的索引
     * @param request 更新商品索引的请求对象
     * @return 处理结果
     * @throws IOException 异常信息
     */
    @Override
    public Boolean updateIndex(IndexRequest request) throws IOException {
        try {
            goodsInfoIndexManager.updateIndex(request.getGoodsInfoMap());
            return true;
        } catch (Exception e) {
            LOG.error("updateIndex发生异常", e);
            return false;
        }
    }

    /**
     * 删除给定的商品索引
     * @param request 删除商品索引的请求对象
     * @return 处理结果
     * @throws IOException 异常信息
     */
    @Override
    public Boolean deleteIndex(IndexRequest request) throws IOException {
        try {
            goodsInfoIndexManager.deleteIndex(request.getGoodsInfoMap());
            return true;
        } catch (Exception e) {
            LOG.error("updateIndex发生异常", e);
            return false;
        }
    }

    /**
     * 初始化索引 全量更新索引
     * @param request 全量更新索引的请求对象
     * @return 是否是生成成功
     * @throws IOException 异常信息
     */
    @Override
    public Boolean addAll(FullUpdateIndexRequest request) throws IOException {
        return goodsInfoIndexManager.addAll(request.getList(), request.getIndex());
    }
}
